package com.newshub.ai.util;

import com.newshub.ai.model.dto.ChartConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 图表生成服务
 */
@Slf4j
@Service
public class ChartGenerator {
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 根据数据和图表类型生成图表配置
     */
    public String generateChartConfig(List<Map<String, Object>> data, String chartType, String title) {
        try {
            ChartConfig chartConfig = new ChartConfig();
            chartConfig.setType(chartType);
            chartConfig.setTitle(title);
            
            switch (chartType.toLowerCase()) {
                case "bar":
                    return generateBarChartConfig(data, title);
                case "line":
                    return generateLineChartConfig(data, title);
                case "pie":
                    return generatePieChartConfig(data, title);
                case "table":
                    return generateTableConfig(data, title);
                default:
                    return generateBarChartConfig(data, title);
            }
        } catch (Exception e) {
            log.error("生成图表配置失败: {}", e.getMessage(), e);
            return generateDefaultChartConfig(data, title);
        }
    }
    
    /**
     * 生成柱状图配置
     */
    private String generateBarChartConfig(List<Map<String, Object>> data, String title) {
        try {
            Map<String, Object> config = new HashMap<>();
            config.put("type", "bar");
            config.put("title", title);
            
            // 提取 X 轴数据（通常是分类或时间）
            List<String> categories = extractCategories(data);
            config.put("xAxis", categories);
            
            // 提取 Y 轴数据（通常是数值）
            List<Number> values = extractValues(data);
            config.put("yAxis", values);
            
            // 系列数据
            Map<String, Object> series = new HashMap<>();
            series.put("name", "数量");
            series.put("data", values);
            series.put("type", "bar");
            
            List<Map<String, Object>> seriesList = Arrays.asList(series);
            config.put("series", seriesList);
            
            return objectMapper.writeValueAsString(config);
        } catch (Exception e) {
            log.error("生成柱状图配置失败: {}", e.getMessage());
            return generateDefaultChartConfig(data, title);
        }
    }
    
    /**
     * 生成折线图配置
     */
    private String generateLineChartConfig(List<Map<String, Object>> data, String title) {
        try {
            Map<String, Object> config = new HashMap<>();
            config.put("type", "line");
            config.put("title", title);
            
            List<String> categories = extractCategories(data);
            config.put("xAxis", categories);
            
            List<Number> values = extractValues(data);
            config.put("yAxis", values);
            
            Map<String, Object> series = new HashMap<>();
            series.put("name", "数量");
            series.put("data", values);
            series.put("type", "line");
            
            List<Map<String, Object>> seriesList = Arrays.asList(series);
            config.put("series", seriesList);
            
            return objectMapper.writeValueAsString(config);
        } catch (Exception e) {
            log.error("生成折线图配置失败: {}", e.getMessage());
            return generateDefaultChartConfig(data, title);
        }
    }
    
    /**
     * 生成饼图配置
     */
    private String generatePieChartConfig(List<Map<String, Object>> data, String title) {
        try {
            Map<String, Object> config = new HashMap<>();
            config.put("type", "pie");
            config.put("title", title);
            
            // 饼图数据格式
            List<Map<String, Object>> pieData = data.stream()
                .map(row -> {
                    Map<String, Object> item = new HashMap<>();
                    String name = String.valueOf(row.values().iterator().next());
                    Number value = (Number) row.values().stream()
                        .filter(v -> v instanceof Number)
                        .findFirst()
                        .orElse(0);
                    item.put("name", name);
                    item.put("value", value);
                    return item;
                })
                .collect(Collectors.toList());
            
            config.put("data", pieData);
            
            return objectMapper.writeValueAsString(config);
        } catch (Exception e) {
            log.error("生成饼图配置失败: {}", e.getMessage());
            return generateDefaultChartConfig(data, title);
        }
    }
    
    /**
     * 生成表格配置
     */
    private String generateTableConfig(List<Map<String, Object>> data, String title) {
        try {
            Map<String, Object> config = new HashMap<>();
            config.put("type", "table");
            config.put("title", title);
            config.put("data", data);
            
            // 提取列头
            if (!data.isEmpty()) {
                List<String> columns = new ArrayList<>(data.get(0).keySet());
                config.put("columns", columns);
            }
            
            return objectMapper.writeValueAsString(config);
        } catch (Exception e) {
            log.error("生成表格配置失败: {}", e.getMessage());
            return generateDefaultChartConfig(data, title);
        }
    }
    
    /**
     * 生成默认图表配置
     */
    private String generateDefaultChartConfig(List<Map<String, Object>> data, String title) {
        try {
            Map<String, Object> config = new HashMap<>();
            config.put("type", "table");
            config.put("title", title);
            config.put("data", data);
            config.put("message", "使用默认表格视图");
            
            return objectMapper.writeValueAsString(config);
        } catch (Exception e) {
            log.error("生成默认图表配置失败: {}", e.getMessage());
            return "{\"error\": \"图表配置生成失败\"}";
        }
    }
    
    /**
     * 提取分类数据（X轴）
     */
    private List<String> extractCategories(List<Map<String, Object>> data) {
        if (data.isEmpty()) return new ArrayList<>();
        
        Map<String, Object> firstRow = data.get(0);
        String categoryKey = firstRow.keySet().stream()
            .filter(key -> !isNumeric(firstRow.get(key)))
            .findFirst()
            .orElse("category");
        
        return data.stream()
            .map(row -> String.valueOf(row.get(categoryKey)))
            .collect(Collectors.toList());
    }
    
    /**
     * 提取数值数据（Y轴）
     */
    private List<Number> extractValues(List<Map<String, Object>> data) {
        if (data.isEmpty()) return new ArrayList<>();
        
        Map<String, Object> firstRow = data.get(0);
        String valueKey = firstRow.keySet().stream()
            .filter(key -> isNumeric(firstRow.get(key)))
            .findFirst()
            .orElse("count");
        
        return data.stream()
            .map(row -> {
                Object value = row.get(valueKey);
                if (value instanceof Number) {
                    return (Number) value;
                }
                try {
                    return Double.parseDouble(String.valueOf(value));
                } catch (NumberFormatException e) {
                    return 0;
                }
            })
            .collect(Collectors.toList());
    }
    
    /**
     * 判断是否为数值类型
     */
    private boolean isNumeric(Object obj) {
        if (obj == null) return false;
        if (obj instanceof Number) return true;
        try {
            Double.parseDouble(String.valueOf(obj));
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}

